# -*- coding: utf-8 -*-
from django.utils import simplejson
from django.contrib.auth.models import User
from socialbar.models import Deal
from socialbar.routePageControl import getData
from socialbar.constants import DEALSSTATUS, keyFromValue
import logging
import re

def userToJson(user):
  string = { 'username' : user.username,
             'test' : '' }
  return simplejson.dumps(string)
  

def getUserFromUserName(username):
  try:
    return User.objects.get(username__exact=username)
  except User.DoesNotExist:
    return None

def getUserFromMail(email):
  try:
    return User.objects.get(email__exact=email)
  except User.DoesNotExist:
    return None    
    
def createAccount(username, mail, password, password2):
  logging.debug('Create account : ' + username + ' & ' + password)  
  if validateEmail(mail) is False:
    return simplejson.dumps({'error' : 'emailBadFormat',
                             'msg' : 'le mail a un mauvais format.'})
  if password != password2:
    return simplejson.dumps({'error' : 'passwordsDontMatch',
                             'msg' : 'Les mots de passe ne correspondent pas.'})
  if getUserFromUserName(username) is not None:
    return simplejson.dumps({'error' : 'usernameTaken',
                             'msg' : 'Ce nom d\'utilisateur a deja ete pris.'})
  if getUserFromMail(mail) is not None:
    return simplejson.dumps({'error' : 'mailTaken',
                             'msg' : 'Cet email est déjà associé à un compte.'})
  user = User.objects.create_user(username, mail, password)
  return simplejson.dumps({'success' : 'userCreated',
                           'msg' : 'Votre compte a bien ete cree.'})


def validateEmail(email):
  if len(email) > 7:
    if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) != None:
      return True
  return False

def buyDeal(request):
  deal = Deal()
  deal.user = request.user
  deal.status = keyFromValue(DEALSSTATUS, 'Bought')
  deal.price = 1
  deal.save()
  dataToDisplay = set(['dealBoughtCount'])
  return simplejson.dumps({'success' : 'dealBought',
                           'data' : getData(request, dataToDisplay)})

def countDeals(user, status):
  if user.is_authenticated() is False:
    return 0
  return len(Deal.objects.filter(user=user,
                           status=keyFromValue(DEALSSTATUS, status)))
def getUserInfo(request):
  profile = {'countDealBought' : countDeals(request.user, 'Bought')}
  return profile








